package com.jorado.trace.util;

import com.jorado.core.utility.UniqueIdUtils;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RequestID {
    /**
     * 请求全局唯一ID，跟踪请求全过程
     */
    private static ThreadLocal<String> requestID = new ThreadLocal<>();
    /**
     * 请求开始时间，可用于统计请求响应时间
     */
    private static ThreadLocal<Long> requestTime = new ThreadLocal<>();

    /**
     * 全局传递的上下文的值
     */
    private static ThreadLocal<Map<String, String>> attachments = ThreadLocal.withInitial(() -> new ConcurrentHashMap<>());

    /**
     * 添加请求的附件
     *
     * @param key
     * @param value
     */
    public static void addAttachment(String key, String value) {
        if (key != null && value != null) {
            attachments.get().put(key, value);
        }
    }

    /**
     * 获取请求的所有的附件
     *
     * @return
     */
    public static Map<String, String> getAttachments() {
        return Collections.unmodifiableMap(attachments.get());
    }

    /**
     * 根据key的名称获取值
     *
     * @param key 全局的键的名称
     * @return
     */
    public static String getAttachment(String key) {
        if (key != null) {
            Map<String, String> kvs = RequestID.attachments.get();
            if (kvs != null) {
                String value = kvs.get(key);
                if (value != null) {
                    return value;
                }
                // 所有x-zp-开头的key，不区分大小写
                if (key.startsWith("x-zp-")) {
                    value = kvs.get("X-ZP-" + key.substring("X-ZP-".length()));
                } else if (key.startsWith("X-ZP-")) {
                    value = kvs.get("x-zp-" + key.substring("x-zp-".length()));
                }
                if (value != null) {
                    //
                    return value;
                }
            }
        }
        return null;
    }

    /**
     * 清空所有的附件
     */
    public static void clearAttachments() {
        if (attachments.get() != null) {
            attachments.get().clear();
        }

    }

    /**
     * 删除请求的附件
     *
     * @param key
     */
    public static void deleteAttachment(String key) {
        if (key != null) {
            attachments.get().remove(key);
        }
    }


    public static void setRequestID(String requestId) {
        requestID.set(requestId);
        requestTime.set(System.currentTimeMillis());
    }

    public static void setRequestID() {
        requestID.set(UniqueIdUtils.generate());
        requestTime.set(System.currentTimeMillis());
    }

    public static String getRequestID() {
        return requestID.get();
    }

    public static Long getRequestTime() {
        return requestTime.get();
    }
}
